const router = require('koa-router')()

const jwt = require('jsonwebtoken');

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  // 数据库测试
  // let sql = 'select * from class'
  // let res = await ctx.db.EXCUTE(sql, [])
  // console.log(res);
  ctx.body = 'koa2 string'
})

router.post('/refreshToken', async (ctx, next) => {
  const refreshToken = ctx.request.body.refreshToken;
  jwt.verify(refreshToken, secret, async (err, decoded) => {
    if (err) {
      ctx.status = 401;
      ctx.body = { error: 'invalid refresh token' };
    } else {
      const { username, userId } = decoded;
      const token = jwt.sign({ username, userId }, secret, { expiresIn: '1h' });
      ctx.body = { token };
    }
  });
});

router.get('/getInfo', async(ctx, next) => {
  let sql1 = `select * from institute 
              join grade on institute.institute_id = grade.institute_id
              join class on grade.grade_id = class.grade_id`;
  let sql2 = "select institute_id, institute_name from institute"
  let res1 = await ctx.db.EXCUTE(sql1, []);
  let res2 = await ctx.db.EXCUTE(sql2, []);
  console.log(res1);
  let obj = {};
  for(let i in res2) {
    
  }
  let arr = [];

  function generateRelations(rows, index = 0, relations = []) {
    if (index === rows.length) {
      return relations;
    }
  
    const currentRow = rows[index];
    const instituteId = currentRow.institute_id;
    const gradeId = currentRow.grade_id;
    const classId = currentRow.class_id;
  
    let institute = relations.find((r) => r.value === instituteId);
    if (!institute) {
      institute = { value: instituteId, label: currentRow.institute_name, children: [] };
      relations.push(institute);
    }
  
    let grade = institute.children.find((g) => g.value === gradeId);
    if (!grade) {
      grade = { value: gradeId, label: currentRow.grade_name, number: currentRow.grade_num, children: [] };
      institute.children.push(grade);
    }
  
    let classObj = grade.children.find((c) => c.value === classId);
    if (!classObj) {
      classObj = { value: classId, label: currentRow.class_name, number: currentRow.class_number };
      grade.children.push(classObj);
    }
  
    return generateRelations(rows, index + 1, relations);
  }
  console.log(generateRelations(res1), "输出数据");
  let infoData = generateRelations(res1);
  ctx.body = {code: 200, msg: "查询成功", infoData}
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})


module.exports = router
